<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 权限表格 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="RolesList" stripe border>
        <!-- 权限展示区 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '','vis']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="closePermissionTagById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过 for 循环 嵌套渲染二级权限 -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop','vis']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="closePermissionTagById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="closePermissionTagById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作" prop="level">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="updataJs(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="romoveUserById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="small" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <!-- 上部区 -->
    <el-dialog title="添加角色信息" :visible.sync="addDialogVisible" width="60%" @close="outForm">
      <el-form :model="addForm" label-width="90px" :rules="editFormRules" ref="clearFrom">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 下部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addJs">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色区 -->
    <!-- 上部区 -->
    <el-dialog title="编辑角色信息" :visible.sync="BjDialogVisible" width="60%" @close="outForm">
      <el-form :model="updataJsFrom" label-width="90px" :rules="editFormRules" ref="clearFrom">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model="updataJsFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:" prop="roleDesc">
          <el-input v-model="updataJsFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 下部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="BjDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updataJsInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="权限分配" :visible.sync="QxdialogVisible" width="50%" @close="setRightDialogClosed">
      <el-tree ref="treeRef" :data="rightsList" :props="QxdefaultProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="QxdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotrights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Roles',
    data () {
      return {
        //角色权限列表数据
        RolesList: [],
        // 所有权限分配数据
        rightsList: [],
        // 权限树形控件
        QxdefaultProps: {
          children: 'children',
          label: 'authName'
        },
        //添加角色数据
        addForm: {
          roleName: '',
          roleDesc: '',
        },
        // 角色用户ID
        roleId: '',
        // 默认选中分配权限的节点Id值数组
        defKeys: [],
        //  添加用户框显示于隐藏添加用户对话框
        addDialogVisible: false,
        // 编辑角色显示于隐藏添加用户对话框
        BjDialogVisible: false,
        // 分配权限对话框显示于隐藏
        QxdialogVisible: false,
        // 添加用户表单规则
        editFormRules: {
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
          ],
        },
        //  查询的角色信息
        updataJsFrom: {},
      }
    },
    created () {
      this.getRolesList()
    },
    methods: {
      // 监听关闭表单
      outForm () {
        // 后清空表单数据
        this.$refs.clearFrom.resetFields();
      },
      // 角色权限列表数据
      async getRolesList () {
        const { data: res } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error('获取角色权限列表失败！')
        }
        this.RolesList = res.data
        // console.log(this.RolesList);
      },
      // 添加角色
      async addJs () {
        this.$refs.clearFrom.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.post('roles', this.addForm)
          if (res.meta.status !== 201) {
            return this.$message.error('创建角色失败,角色名称不能为空')
          }
          this.addDialogVisible = false
          this.getRolesList()
        })
      },
      //查询角色信息
      async updataJs (id) {
        this.BjDialogVisible = true
        const { data: res } = await this.$http.get(`roles/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('查询角色信息失败')
        }
        this.updataJsFrom = res.data

        // console.log(id);
        // console.log(this.updataJsFrom);
      },
      // 修改角色信息
      updataJsInfo () {
        this.$refs.clearFrom.validate(async valid => {
          if (!valid) return
          // 发起修改角色求请
          const { data: res } = await this.$http.put(`roles/${this.updataJsFrom.roleId}`, {
            roleName: this.updataJsFrom.roleName,
            roleDesc: this.updataJsFrom.roleDesc
          })
          console.log(res);

          if (res.meta.status !== 200) {
            this.$message({
              duration: 600,
              message: '修改角色信息失败',
              type: 'error'
            });
          }
          this.$message({
            duration: 600,
            message: '修改角色信息成功',
            type: 'success'
          });
          this.BjDialogVisible = false
          this.getRolesList()
        })
      },
      // 根据ID删除角色信息
      async romoveUserById (id) {
        const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // console.log(confirmResult);
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除角色信息')
        }
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除角色信息失败')
        }
        this.$message.success('删除角色信息成功')
        this.getRolesList()
      },
      // 根据Id删除角色展开权限标签事件
      async closePermissionTagById (role, rightId) {
        const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') {
          return this.$message.info('以取消删除')
        }
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightId}`
        )
        if (res.meta.status !== 200) {
          return this.$message.error('删除权限失败！')
        }
        // this.getRolesList()
        role.children = res.data
      },
      // 分配权限对话框
      async showSetRightDialog (role) {
        // 获取权限分配数据
        const { data: res } = await this.$http.get('rights/tree')
        if (res.meta.status !== 200) {
          return this.$message.error('删除所有权限失败')
        }
        this.rightsList = res.data
        this.getLeafKeys(role, this.defKeys)
        this.QxdialogVisible = true
        // console.log(this.rightsList);
        // console.log(this.defKeys);
        this.roleId = role.id
      },
      // 通过递归的形式，获取用户下所有的权限ID，并保存到defKey数组中
      getLeafKeys (node, arr) {
        // 如果当前node节点不包含Children属性，则为三级节点
        if (!node.children) {
          return arr.push(node.id)
        }
        node.children.forEach(item => {
          this.getLeafKeys(item, arr)

        })
      },
      // 监听分配权限对话框关闭
      setRightDialogClosed () {
        this.defKeys = []
      },
      // 为角色分配权限
      async allotrights () {
        const treeKeysArr = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
        const treeNewKeysArr = treeKeysArr.join(',')
        const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: treeNewKeysArr })
        // console.log(res);
        // console.log(this.roleId);
        if (res.meta.status !== 200) {
          return this.$message.error('分配权限失败')
        }
        this.$message.success('分配权限成功')
        this.getRolesList()
        this.QxdialogVisible = false
      },

    }

  }
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>